package com.example.java_springboot_uploadimg.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;

// 图片上传参考b站视频 https://www.bilibili.com/video/BV1TK411Z7ad/?spm_id_from=333.337.search-card.all.click&vd_source=125d808bbbad2b8400f221b816a0f674
// 原文链接：https://blog.csdn.net/ALemon_Y/article/details/71436194

@RestController
public class helloController {

    // 写入文件
    private boolean writeFile(String content, String targetPath){
        try {
            if(content != null){
                // String json = JSONObject.toJSONString(content);
                File file = new File(targetPath);
                FileUtils.writeStringToFile(file, content,"UTF-8",false);
                return true;
            }
        }catch (IOException e){
            System.out.println("error-writeFile: "+e);
        }
        return false;
    }

    // 读取文件
    public JSONArray readFile(String filePath) throws IOException {
        File file = new File(filePath);
        String content = FileUtils.readFileToString(file,"UTF-8");
        System.out.println("content:"+content);
        JSONArray arr = JSON.parseArray(content);
        System.out.println("jsonObject:"+arr);

        // System.out.println("姓名是："+jsonObject.getString("name"));
        // System.out.println("年龄："+jsonObject.getDouble("age"));
        // System.out.println("学到的技能："+jsonObject.getJSONArray("major"));
        // System.out.println("国家："+jsonObject.getJSONObject("Nativeplace").getString("country"));
        // 原文链接：https://blog.csdn.net/ALemon_Y/article/details/71436194
        return arr;
    }

    public String getJsonPath(){
        String projectPath = this.getProjectPath();
        projectPath = projectPath + "//src//main//resources//me.json";
        return projectPath;
    }

    @GetMapping("/getData")
    public JSONArray getData() throws IOException {
        String projectPath = this.getJsonPath();
        JSONArray object = this.readFile(projectPath);
        return object;
    }

    @PostMapping("/upload")
    public JSONArray upload(MultipartFile file) throws IOException {
        System.out.println("有人进来----");

        // 1.获取文件名
        String fileName = file.getOriginalFilename();
        Integer index = fileName.lastIndexOf(".");
        Integer pointIndex = fileName.length()-(fileName.length()-index);
        String name = fileName.substring(0,pointIndex);
        String etc = fileName.substring(pointIndex);
        System.out.println("后缀："+etc);
        // 2.给文件重命名，避免重复覆盖的情况
        String uuid = UUID.randomUUID().toString().replace("-","");
        uuid = uuid.substring(0, 10);
        fileName = name+"_"+uuid+etc;
        System.out.println("fileName："+fileName);
        // 3.获取要存储的路径
        String targetPath = "";
        targetPath = this.getProjectPath();
        targetPath = targetPath + "//src//main//resources//static//images//" + fileName;
        // 4.写入文件
        try{
            file.transferTo(new File(targetPath));
            // 读取json文件
            String jsonPath = this.getJsonPath();
            JSONArray arr = this.readFile(jsonPath);
            Map map = new HashMap();
            map.put("name", name);
            map.put("img", "images/"+fileName);
            JSONObject obj = new JSONObject(map);

            arr.add(obj);
            System.out.println("数据："+arr);
            // 重新写入文件保存 SerializerFeature.PrettyFormat 是重点，格式化写入美观
            // 参考网址 https://www.jb51.net/article/197667.htm
            this.writeFile(JSONArray.toJSONString(arr, SerializerFeature.PrettyFormat), jsonPath);

            // 返回前端
            return arr;
        } catch (IOException e){
            e.printStackTrace();
        }
        return new JSONArray();
    }

    public String getProjectPath(){
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String targetPath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
        return targetPath;
    }
}
